/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package impresos;

import gestion.FEstadisticas.DatosEstad;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.*;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import otros.Configuracion;
import otros.Fecha;
import otros.Util;
import tablasSql.ConsultaBD;

/**
 *
 * @author FERRETERIA
 */


class ObjetoDeImpEstad extends Component implements Printable{
    
    private DatosToImprimir d;
    int posY;
    int NUM_LINEAS;
   
    
    public ObjetoDeImpEstad (DatosToImprimir d, int tamLineas) {
        super();
        NUM_LINEAS = tamLineas;
        this.d = d;
    } 
    
    private int getIniPosX() { 
       return 56;
    }
        
    public void EncabezadoA4(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
         
        int y = 10;
        posY = 80;
        int posX = getIniPosX();
        
        g.setFont(new Font ("Calibri", Font.BOLD, 16));
        g.drawString(d.getFecha(), posX, posY);      // x,y
        g.setFont(new Font ("Calibri", Font.PLAIN, 12));
        g.drawString("Pag.: "+(d.getPagina()+1), 450,posY);
        g.drawString("Nº Total Lineas: "+d.getNumCopias(), posX,posY+=13);
  
        g.drawLine(posX, posY +=5, 540, posY);
    }
    
    private int desplazar(int i) {
        switch(i) {
            case 0:
                return 100;
            case 1:
                return 150;
            case 2:
                return 390;
            default:
                return 0;
        }
    }
    
    private String DarFormato(String num) {
        String result = "";
        int numDigit = 11;
        
        for (int i = 0; i < numDigit - num.length(); i++) {
            result += " "; 
        }
        result += num;
        return result;
    }
    
    
    public void Datos(Graphics g) {
        int posX = getIniPosX();
        int y;
        
        Map<String, DatosEstad> datos = d.getDatosEstad();
        DatosEstad dE = null;
        //int x = 0;
        
        y = 14;
        posY += y;
        g.setFont(new Font ("Consolas", Font.PLAIN, 10));
        Iterator itM = datos.entrySet().iterator();
        Map.Entry <String, DatosEstad> mE = null;
        if (d.getPagina() > 0) {
            while (itM.hasNext()) {
                mE = (Map.Entry) itM.next();
                if (mE.getKey().equals(d.getiKeys().get(d.getPagina()-1)))
                    break;
            }
	}
        else
            mE = (Map.Entry) itM.next();
        int j = 0;
        boolean primer = true;
        String key = null;
        do {
            if (!primer)
                mE = (Map.Entry) itM.next();
            key = mE.getKey();
            dE = datos.get(key);
            
            int iList = primer && (d.getPagina() > 0) ? d.getiPos().get(d.getPagina()-1): 0;
            if (iList == 0) {
                g.drawString(Fecha.formatFecha(key), posX, posY + y * j);                
                g.drawString("VENTAS", posX + desplazar(0), posY + y * j);
                g.drawString(DarFormato(Util.getFormatPrecio(dE.ventas,2)), posX + desplazar(2), posY + y * j);
                j++;
            }
            if(dE.comp != null) {
                int i;
                for (i = iList; (i< dE.comp.size()) && (j < NUM_LINEAS); i++) {
                    g.drawString("GASTOS", posX + desplazar(0), posY + y * j);
                    g.drawString(dE.compProv.get(i), posX + desplazar(1), posY + y * j);
                    g.drawString(DarFormato(Util.getFormatPrecio(dE.comp.get(i),2)), posX + desplazar(2), posY + y * j);
                    j++;
                }
                if (i < dE.comp.size()) {
                    d.getiPos().add(d.getPagina(), i);
                }
                primer = false;        
            }
            
        } while(itM.hasNext() && (j < NUM_LINEAS));
        
        if(j >= NUM_LINEAS)
            d.getiKeys().add(d.getPagina(), key);
    }
    
    public void Pie(Graphics g) {
       posY = 770;
       int posX = getIniPosX();
       g.drawLine(posX, posY, 540, posY);
       String fuente = "Arial";
       //if (d.getPagina()+1 == d.getTotalPaginas()) {
          g.setFont(new Font (fuente, Font.BOLD, 10));
          g.drawString("Ventas del mes: " + Util.getFormatPrecio(d.getTotales()[0],2), posX + desplazar(1), posY+=14);
          g.drawString("Gastos del mes: " + Util.getFormatPrecio(d.getTotales()[1],2), posX + desplazar(1), posY+=14);
    }
               
    public int print(Graphics g, PageFormat f, int pageIndex){
        if (d.getTotalPaginas() > pageIndex) {
           d.setPagina(pageIndex % d.getTotalPaginas()); 
           EncabezadoA4(g);
           Datos(g); 
           Pie(g);
           return PAGE_EXISTS;
        }
        else
            return NO_SUCH_PAGE;
    }
}

public class ImpEstadisticas {
    
    static final int NUM_LINEAS = 47;
    static String impresora;
    
    void Imprimir () {
        setImpresora(false);
    }
    
    static void setImpresora (boolean pdf) {
        if (pdf)
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_PDF);
        else
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_NORMAL);
    }
    
    static public void imprime(DatosToImprimir d, boolean pdf){
        ConsultaBD.cursorEspera(null);
        setImpresora(pdf);
        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        Paper paper = new Paper();
        double margin;
        paper.setSize(595.0,842.0); // ancho y alto  A4
        margin = 10;
        
        
        paper.setImageableArea(margin, margin, paper.getWidth()-margin, paper.getHeight()-margin);
        pf.setPaper(paper);
        pf.setOrientation(PageFormat.PORTRAIT);  // vertical
        job.setJobName("Imp-Estad-" + d.getFecha());
        
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : services) {
            if (printService.getName().equals(impresora)) {
                try {
                    job.setPrintService(printService);
                    break;
                } catch (PrinterException ex) {
                    System.out.println(ex);
                }
            }
        }
        try{
            int tamLista = d.getNumCopias();
            int hojas = tamLista/NUM_LINEAS;
            if (tamLista%NUM_LINEAS == 0)
               hojas--;
            d.setTotalPaginas(hojas); 
            ArrayList<Integer> a = new ArrayList<Integer> ();
            ArrayList<String> b = new ArrayList<String> ();
            for (int i = 0; i < hojas; i++) {
                a.add(0);
                b.add(null);
            }
            d.setiPos(a);
            d.setiKeys(b);
            job.setPrintable(new ObjetoDeImpEstad(d, NUM_LINEAS), pf);  
            job.print();
        } catch(PrinterException e){
             System.out.println(e);
        } 

        ConsultaBD.cursorNormal(null);
    }
}
